package com.wj.graph;

import com.wj.linear.Stack;

/**
 * @author wen.jie
 * @date 2021/8/27 14:21
 */
public class DepthFirstPaths {
    // 索引代表顶点，值表示当前顶点是否已经被搜索
    private boolean[] marked;
    //起点
    private int s;
    //索引代表顶点，值代表从起点s到当前顶点路径上的最后一个顶点
    private Integer[] edgeTo;

    public DepthFirstPaths(Graph G,int s){
        this.marked = new boolean[G.V()];
        this.s = s;
        this.edgeTo = new Integer[G.V()];
        dfs(G, s);
    }

    private void dfs(Graph G, int v){
        marked[v] = true;
        for (Integer w : G.adj(v)) {
            if(!marked[w]) {
                //到达顶点w的路径上的最后一个顶点是v
                edgeTo[w] = v;
                dfs(G, w);
            }
        }
    }

    //判断v顶点与s顶点是否存在路径
    public boolean hasPathTo(int v){
        return marked[v];
    }

    //找出从起点s到顶点v的路径(就是该路径经过的顶点)
    public Stack<Integer> pathTo(int v){

        if (!hasPathTo(v))
            return null;
        Stack<Integer> path = new Stack<>();
        path.push(v);
        while (edgeTo[v] != null) {
            int p = edgeTo[v];
            path.push(p);
            v = p;
        }
        return path;
    }
}
